;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Barcode.UnboxingPrint", [])
        .controller("UnboxingPrintCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showPrintConf: false
            };
            $scope.detailInfo = {};
            $scope.markInfo = {};
            $scope.showDatepickerBegin = false;
            $scope.showDatepickerEnd = false;
            $scope.condition = {
                beginDate: ybWidget.FormatStartDate(+new Date()),
                endDate: ybWidget.FormatEndDate(+new Date()),
                barcodeFlag: 1
            };
            $scope.tempSet = {
                qrCodeSize: 85,
                printMainCode: true,
            };
            $scope.packList = [];
            $scope.dataList = [];
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1460,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "原始数量",
                        dataField: "totalQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "打印数量",
                        dataField: "currentQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusDesc",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "操作时间",
                        dataField: "createTimeShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "操作人",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据号",
                        dataField: "billNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "条码",
                        dataField: "barcode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "条码类型",
                        dataField: "barcodeFlagShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "VIN码",
                        dataField: "vinid",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "图号",
                        dataField: "orawyd",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "条码描述",
                        dataField: "barcodeDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "规格描述",
                        dataField: "model",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            var lodop;
            $scope.printInfo = {};

            var btnPermissionCode = {
                unboxingPrintPrint: window.ActionCode.unboxingPrintPrint
            };

            $scope.btnPermission = {
                unboxingPrintPrint: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}};
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                if ($scope.dataList[index].currentQty < 1) {
                    ybWidget.ShowToaster('error', '打印数量至少为1才可拆箱');
                    return;
                }
                if ($scope.dataList[index].barcodeStatus !== '0' && $scope.dataList[index].barcodeStatus !== '1' && $scope.dataList[index].barcodeStatus !== '2') {
                    ybWidget.ShowToaster('error', '条码状态不可拆分');
                    return;
                }
                $scope.markInfo.cueRow = index;
                $scope.currentMaterial = $scope.dataList[index];
                $scope.detailInfo.totalQty = angular.copy($scope.currentMaterial.currentQty);
                $scope.detailInfo.packNum = 2;
                $scope.packList = [{
                    currentQty: parseInt($scope.currentMaterial.currentQty / 2),
                    vinid: ''
                }, {
                    currentQty: Number(($scope.currentMaterial.currentQty - parseInt($scope.currentMaterial.currentQty / 2)).toFixed(3)),
                    vinid: ''
                }];
            };
            $scope.countPack = function () {
                $scope.detailInfo.packNum = parseInt($scope.detailInfo.packNum);
                //$scope.detailInfo.totalQty = parseInt($scope.detailInfo.totalQty);
                // if ($scope.detailInfo.totalQty < $scope.detailInfo.packNum) {
                //     $scope.detailInfo.totalQty = $scope.detailInfo.packNum;
                // }
                setEachPack();
            };

            $scope.setPackNum = function () {
                $scope.detailInfo.packNum = parseInt($scope.detailInfo.packNum);
                //$scope.detailInfo.totalQty = parseInt($scope.detailInfo.totalQty);
                // if ($scope.detailInfo.packNum > $scope.detailInfo.totalQty) {
                //     $scope.detailInfo.packNum = $scope.detailInfo.totalQty;
                // }
                setEachPack();
            };
            function setEachPack() {
                $scope.packList = [];
                var eachPackNum = Math.floor($scope.detailInfo.totalQty / $scope.detailInfo.packNum);
                for (var i = 0; i < $scope.detailInfo.packNum; i++) {
                    var objData = {
                        currentQty: eachPackNum,
                        vinid: ''
                    };
                    if (i == $scope.detailInfo.packNum - 1) {
                        objData.currentQty = Number((objData.currentQty + $scope.detailInfo.totalQty % $scope.detailInfo.packNum).toFixed(3));
                        $scope.packList.push(objData);
                    } else {
                        $scope.packList.push(objData);
                    }
                }
            }

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
                $scope.condition.beginDate = +new Date() - 86400000;
                $scope.condition.endDate = +new Date();
                $scope.condition.barcodeFlag = 1;
            };

            $scope.previewOrPrintTicket = function (type) {
                if ($scope.packList.length < 2) {
                    ybWidget.ShowMessage('至少要有两个包装');
                    return;
                }
                var amount = 0;
                angular.forEach($scope.packList, function (item) {
                    amount = Number((amount + parseFloat(item.currentQty)).toFixed(3));
                    item.barcodeDesc = $scope.detailInfo.barcodeDesc;
                    item.model = $scope.detailInfo.model;
                    item.orawyd = $scope.detailInfo.orawyd;
                });
                if (amount != $scope.detailInfo.totalQty) {
                    ybWidget.ShowMessage('每包数量之和必须等于原条码打印数量');
                    return;
                }
                var param = {
                    barcode: $scope.currentMaterial.barcode,
                    detailList: $scope.packList
                };
                ybHttp.Post('device', '/barcode/splitPrint', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    startPrint(type, resp.value, false);
                });
            };

            $scope.printList = [];
            async function startPrint(type, printListArr, isBatch) {
                if (!$scope.tempSet.printMainCode) {
                    for (var i = 0; i < printListArr.length; i++) {
                        if (printListArr[i].barcodeFlag === 0) {
                            printListArr.splice(i, 1);

                            if (!isBatch) { // 非批量打印，只有一个总条码，找到 即 退出for循环
                                break;
                            }
                        }
                    }
                }

                $scope.printList = type === "preview" && printType !== 1 ? printListArr : UserContextService.ListGroup(printListArr, 20);

                var printType = $scope.tempSet.printType;
                lodop = UserContextService.GetLodop();
                if (!lodop) {
                    return;
                }

                if (!await UserContextService.InitPrinter(lodop, true, printType)) {
                    return;
                }

                setTimeout(function () {
                    UserContextService.ListPrint($scope.printList, lodop, printType, type === "preview");

                    $scope.printList = [];
                    getDataList();
                }, 300)
            }

            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };
            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/barcode/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                $scope.condition.beginDate = new Date($scope.condition.beginDate).getTime();
                $scope.condition.endDate = new Date($scope.condition.endDate).getTime();
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    $scope.markInfo.allChecked = false;
                    angular.forEach($scope.dataList, function (item) {
                        item.isChecked = false;
                        item.barcodeFlagShow = item.barcodeFlag ? '分条码' : '总条码';
                        item.packNum = item.currentQty;
                        item.createTimeShow = $filter("YbDate")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                    })
                });
            }

            (function () {
                // getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);